export default class api_protobuf {
    private pbc:any         = null; //probuff
    private don:any         = null; //完成回调
    private idx:number      = 0;
    private pth:string[]    = [
        "./pbd/message",            //通用协议
        "./pbd/login",              //登陆协议
        "./pbd/lobby",              //大厅协议
        "./pbd/game",               //游戏协议
        "./pbd/game/slots/slots",   //金玉满堂
    ];
    //构造
    constructor(don:any){
        this.don = don;
        this.parse();
    }

    //解析
    public parse():any{
        let idx = this.idx++;
        if(idx >= this.pth.length){
            this.don();
            return;
        }
        let url = this.pth[idx];
        cc.loader.loadRes(url,(err, text) => {
            if(this.pbc == undefined){
                this.pbc = protobuf.parse(text);
            }
            else{
                protobuf.parse(text,this.pbc.root);
            }
            this.parse();
        })
    }

    //编码
    public encode(name:string,data:any):Uint8Array {
        let res = this.pbc.root.lookupType(name);
        let msg = res.create(data)
        let pck = res.encode(msg).finish()
        return pck
    }

    //解码
    public decode(name:string,pck:ArrayBuffer):any {
        let res = this.pbc.root.lookupType(name);
        let buf = new Uint8Array(pck)
        let msg = res.decode(buf)
        return msg
    }

    //编码
    public encode_message(name:string,cmds:string[],info:msgBody):ArrayBuffer{
        let head = this.encode("msgHead",{name:name,cmds:cmds})
        let body = this.encode(name,info)
        let size = head.byteLength + body.byteLength
        let data = new ArrayBuffer(size+2)
        let view = new DataView(data)
        let sort = 0
        let leng = head.byteLength
        view.setUint8(sort++,Math.floor(leng/256))
        view.setUint8(sort++,Math.floor(leng%256))

        for (let index = 0; index < head.byteLength; index++) {
            view.setUint8(sort++,head[index])
        }
        for (let index = 0; index < body.byteLength; index++) {
            view.setUint8(sort++,body[index])
        }
        return data;
    }

    //解码
    public decode_message(pack:ArrayBuffer):msgBody{
        let view = new DataView(pack);
        let headsize = view.getUint8(0)*256 + view.getUint8(1)
        let head = this.decode("msgHead",pack.slice(2,2+headsize));
        let name = head.name;
        let body = this.decode(name,pack.slice(2+headsize));
        let cmds:string[] = head.cmds
        cmds.push(name)
        cmds.reverse()
        return {
            name:name,
            cmds:cmds,
            info:body,
        };
    }
}